<template>
  <div class="alarm-wrap">
<!--    <div class="info-box" @click="showInfo">-->
<!--      <img src="~assets/img/huojing.png" @click="fnShow"/>-->
<!--      <span class="alarmNum" v-if="alertInfoArr.length > 0">{{ alertInfoArr.length }}</span>-->
<!--    </div>-->
    <Telport to="body">
      <el-dialog
          :title="title"
          :visible.sync="showModal"
          :close-on-click-modal="false"
          :before-close="fnClose"
          width="60%">
<!--        <video controls style="position:relative;z-index:9999;width: 100%;height: 100%;" src="http://f.video.weibocdn.com/o0/ufOkLKY4lx083bVkNbmo01041202j50I0E010.mp4?label=mp4_hd&template=852x480.25.0&media_id=4869755308539960&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=2&ot=h&ps=3lckmu&uid=3ZoTIp&ab=,8143-g0,8013-g0,3601-g33,7598-g0&Expires=1677077548&ssig=3Ywug489Nx&KID=unistore,video"></video>-->
        <div class="videoWrap" id="videoWrap">
          <!--ws://52.131.47.150:46000/live/000.flv?tik=224a121104154429137864d5821ac6a1&tikpwd=-->
          <VideoWs id="selectFiles" @click="fnSet"  v-if="videoShow" style="position:relative;z-index:9999;width: 100%;height: 100%;" :url="stream"></VideoWs>
        </div>
      </el-dialog>
    </Telport>
    <!--    <div
          class="alert-box"
          v-if="
            alertInfoShow && Array.isArray(alertInfoArr) && alertInfoArr.length > 0
          "
        >
          &lt;!&ndash;初始显示&ndash;&gt;
          <el-alert
            :title="alertInfoArr[0].datas.title"
            :type="alertInfoArr[0].datas.type == 2 ? 'success' : 'info'"
            :description="formatTime(alertInfoArr[0].datas.ts)"
            show-icon
            @close="close_alart"
          >
          </el-alert>
        </div>
        &lt;!&ndash;点击显示全部&ndash;&gt;
        <div class="click-box" v-if="click_alert_show">
          <div class="message-box">
            <el-alert
              show-icon
              v-for="(item, index) in alertInfoArr"
              :key="index"
              :title="item.datas.title"
              :type="item.datas.type == 2 ? 'success' : 'info'"
              :description="formatTime(item.datas.ts)"
              @close="close_alart"
            >
            </el-alert>
          </div>

          <div class="btn-wrap-fixed">
            <el-button
              type="primary"
              plain
              size="mini"
              class="clear_arr"
              @click="clear_arr"
              >清空</el-button
            >
            <el-button
              type="primary"
              plain
              size="mini"
              class="close_arr"
              @click="close_arr"
              >关闭</el-button
            >
          </div>
        </div>-->
  </div>
</template>

<script>
import { getYMDHMS } from "@/utils/Tool";
import { postData } from "@/request/http";
import VideoWs from './Video'
import Telport from "./Telport";
window.reStartStatusHuo = true;
export default {
  name: "Alarm",
  data() {
    return {
      alertInfoArr: [],
      path: "",
      socket: null,
      timer: null,
      reStartStatusHuo: true,
      alertInfoShow: false,
      click_alert_show: false,
      stream: null,
      showModal: false,
      videoShow: false,
      title: "",
      reopen: true,  // 可爱善良漂亮的猴总，要不要考虑结工资
    };
  },
  mounted() {

    // let _path = window.baseUrl + "websocket";
    // let _path = 'http://192.168.1.77:8080/websocket'
    // if (_path.indexOf("https") == 0) {
    //   let path_https = _path.replace(/https/g, "ws");
    //   this.path = path_https;
    // } else {
    //   let path_http = _path.replace(/http/g, "ws");
    //   this.path = path_http;
    // }
    // setTimeout(()=> {
    //   this.showModal = true
    //   setTimeout(()=> {
    //     this.videoShow = true
    //   }, 1000)
    // }, 1000)
    this.alertInfoArr = []
    this.stream = ''
    this.title = ''
    if (process.env.NODE_ENV === "development") {
      this.path = 'ws://ydts3.hbwlife.com/websocket';
    } else if (process.env.NODE_ENV === "production") {
      this.path = "ws://" + window.location.host+"/websocket";
    }

    this.initWs();

    if (window.mysocketHuo) {
      window.reStartStatusHuo = false;
      window.mysocketHuo.close();
      if (window.timerWsHuo) {
        clearInterval(window.timerWsHuo);
      }
      this.initWs();
    } else {
      if (window.timerWsHuo) {
        clearInterval(window.timerWsHuo);
      }
      this.initWs();
    }
  },
  computed: {
    username() {
      return this.$store.state.login.username;
    },
  },
  methods: {
    //初始ws
    initWs() {
      let that = this;
      window.mysocketHuo = null;
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        window.mysocketHuo = that.socket = new WebSocket(that.path);
        // 监听socket连接
        window.mysocketHuo.onopen = that.open;
        // 监听socket错误信息
        window.mysocketHuo.onerror = that.error;
        // 监听socket消息
        window.mysocketHuo.onmessage = that.getMessage;
        // 关闭 socket消息
        window.mysocketHuo.onclose = that.close;
      }
    },
    fnSet(){
      console.log("点击了")
    },
    open() {
      console.log("WS connected!");
      this.send();
    },
    send() {
      window.mysocketHuo.send(
        JSON.stringify({
          action: "sys/websocket/register",
          user_name: localStorage.getItem("username"),
          token: localStorage.getItem("token"),
          datas: {
            session_id: new Date().getTime(),
          },
        })
      );
    },
    async getMessage(msg) {
      let nowMsg = JSON.parse(msg.data);
      if (nowMsg.connection == "close") {
        window.reStartStatusHuo = false;
        if (window.timerWsHuo) {
          clearInterval(window.timerWsHuo);
        }
        window.mysocketHuo.close();
        return;
      }
      if (nowMsg.action == "sys/websocket/register" && nowMsg.code == 0) {
        window.wsTimeHuo = nowMsg.datas.heartbeat_interval;
        this.heartWs();
      }
      if (nowMsg.action == "device/general/message" && nowMsg.code == 0) {
        nowMsg.title = nowMsg?.datas?.title || '';
        nowMsg.ts = nowMsg.datas.ts;
        nowMsg.sn = nowMsg.datas.sn

        this.alertInfoArr.push({
          sn: nowMsg.sn,
          ts: nowMsg.ts,
          title: nowMsg.title
        })

        // 可爱的猴，看这 this.reopen就是是否再次打开开关
        if(!this.showModal && this.reopen){
          let sn = this.alertInfoArr[this.alertInfoArr.length - 1]['sn']
          let datas = await postData("/adminweb/device/stream/live/url/ticket/lasted/unlimited", {
            sn: sn,
            ptl: "WS-FLV",
            sub: 0,
          })
          this.stream = datas?.datas?.stream || ""
          let dataArr = this.alertInfoArr.filter(item => item.sn == sn)
          this.title = dataArr.length > 0 && dataArr[0].title || ""
          this.showModal = true
          setTimeout(()=> {
            this.videoShow = true
            console.log(this.stream)
          }, 1000)
        }
        // this.alertInfoArr.unshift(nowMsg);
        // this.alertInfoShow = true;
        // var timer;
        // if (timer) {
        //   clearTimeout(timer);
        // }
        // timer = setTimeout(() => {
        //   this.alertInfoShow = false;
        // }, 3000);
      }
    },
    async fnShow(){
      if(!this.alertInfoArr || Array.isArray(this.alertInfoArr) && this.alertInfoArr.length == 0){
        return
      }
      if(!this.showModal){
        this.showModal = true
        let len = this.alertInfoArr.length;
        let item = this.alertInfoArr[len - 1] || {}
        if(item && item['sn']){
          let datas = await postData("/adminweb/device/stream/live/url/ticket/lasted/unlimited", {
            sn: item['sn'],
            ptl: "WS-FLV",
            sub: 0,
          })
          this.stream = datas?.datas?.stream || ""
          this.title = item.title
          this.alertInfoArr = []
          setTimeout(()=> {
            this.videoShow = true
          }, 1000)
        }
      }
    },

    // 可爱的大眼睛，看这，这里是关闭  你这只是关闭的逻辑 我要的是按钮的html 在哪写着
    fnClose(){
      this.videoShow = false
      this.showModal = false
      this.reopen = false
    },
    close() {
      console.log("WS Closed!");
      this.videoShow = false
      this.showModal = false
      if (window.timerWsHuo) {
        clearInterval(window.timerWsHuo);
      }
      if (window.mysocketHuo && window.reStartStatusHuo) {
        this.initWs(); //断开、刷新后重连
      }
    },
    error() {
     // console.log("connecte fail");
    },
    /* 
    心跳服务
    */
    heartWs() {
      if (window.mysocketHuo && window.wsTimeHuo) {
        window.timerWsHuo = setInterval(() => {
          window.mysocketHuo.send(
            JSON.stringify({
              action: "ping",
              user_name: localStorage.getItem("username"),
              token: localStorage.getItem("token"),
            })
          );
        }, window.wsTimeHuo * 1000);
      }
    },

    //点击的时候显示消息弹窗
    showInfo() {
      if (this.alertInfoArr.length > 0) {
        this.click_alert_show = true; //显示，点击弹窗
      }
    },

    //关闭 弹窗
    close_alart() {
      this.click_alert_show = false;
    },
    //清空按钮
    clear_arr() {
      // sessionStorage.clear();
      this.click_alert_show = false;
      this.alertInfoArr = [];
    },
    //关闭按钮
    close_arr() {
      this.click_alert_show = false;
    },
    //格式时间
    formatTime(time) {
      return getYMDHMS(time);
    },
    beforeMountbe() {
      this.click_alert_show = false;
    },
    destroyed() {
      this.click_alert_show = false;
    },
  },
  components:{
    VideoWs,
    Telport
  }
};
</script>

<style scoped>
.alarm-wrap {
  width: 20px;
  height: 20px;
  float: left;
}
.alarm-wrap img {
  width: 100%;
  height: 100%;
}
.info-box{
  position: relative;
}
.alarmNum {
  background-color: #da2727;
  position: absolute;
  right: -10px;
  top: -8px;
  width: auto;
  height: auto;
  line-height: 17px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  border-radius: 50%;
  /* padding:2px; */
  padding: 2px 6px;
}
.alert-box {
  position: absolute;
  right: 0;
  width: auto;
  min-width: 500px;
  height: auto;
  display: flex;
  flex-flow: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
  /* background:rgb(0, 0, 0, 0.3);
  border-radius:10px; */
}
.click-box {
  position: absolute;
  top: 0;
  right: 0;
  width: 500px;
  height: auto;
  max-height: 600px;
  /* overflow-y:scroll; */
  display: -ms-flexbox;
  -ms-flex-flow: column;
  -ms-flex-pack: start;
  -ms-flex-align: center;
  padding: 20px;
  padding-top: 50px;
  background: #f7fbf7;
  border-radius: 10px;
  overflow: hidden;
}
.message-box {
  width: 100%;
  /* height: 500px; */
  height: auto;
  overflow-y: scroll;
}
/* .btn-wrap-fixed{
    position:fixed;
    top:0;
    right:0;
} */
.clear_arr {
  position: absolute;
  right: 90px;
  top: 8px;
}
.close_arr {
  position: absolute;
  right: 20px;
  top: 8px;
}
.alert-box >>> .el-alert {
  margin-bottom: 10px;
}
/* .alert-box >>> .el-alert--error.is-light .el-alert__description {
  color:#898b8e;
}
.alert-box >>> .el-alert.is-light .el-alert__closebtn {
  color:#000;
  font-size:14px;
}
.alert-box >>> .el-alert__title{
    color:rgb(199, 42, 42);
}
.alert-box >>> .el-alert__icon.is-big{
    color:rgb(199, 42, 42);
} */

.alert-box >>> .el-alert.is-light .el-alert__closebtn {
  opacity: 0;
}
.click-box >>> .el-alert.is-light .el-alert__closebtn {
  opacity: 0;
}
.videoWrap{
  width: 100%;
  height: 100%;
  background-color: #000;
}
</style>
<style>
.el-dialog{
  z-index: 9999!important;
}
</style>